package com.gzhryc.shared_device.oem.h5.mng.controllers;

import com.gzhryc.common.NumberTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.echars.*;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.common.secruity.VerifyCodeTools;
import com.gzhryc.common.secruity.VerifyCodeTools.VerifyCode;
import com.gzhryc.dictionary.dao.db.CountryArea;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.common.CountryAreaUtils;
import com.gzhryc.shared_device.common.device.services.DeviceService;
import com.gzhryc.shared_device.common.device.services.dto.DeviceSearch;
import com.gzhryc.shared_device.common.payment.dao.enums.ProjectWalletEnum;
import com.gzhryc.shared_device.oem.code.BaseConstants;
import com.gzhryc.shared_device.oem.code.agent.services.AgentService;
import com.gzhryc.shared_device.oem.code.agent.services.dto.AgentSearch;
import com.gzhryc.shared_device.oem.code.member.services.MemberWalletService;
import com.gzhryc.shared_device.oem.code.place.services.PlacePhysicalStoreService;
import com.gzhryc.shared_device.oem.code.place.services.dto.PlacePhysicalStoreSearch;
import com.gzhryc.shared_device.oem.code.profit.service.ProjectWalletService;
import com.gzhryc.shared_device.oem.code.statistics.dao.db.ProjectProfitDayStatistics;
import com.gzhryc.shared_device.oem.code.statistics.services.ProjectProfitDayStatisticsService;
import com.gzhryc.shared_device.oem.code.user.services.UserWalletService;
import com.gzhryc.shared_device.oem.code.statistics.dao.db.ProjectDayStatistics;
import com.gzhryc.shared_device.oem.code.statistics.dao.models.ProjectSumMoneyData;
import com.gzhryc.shared_device.oem.code.statistics.dao.models.ProvinceSumMoneyData;
import com.gzhryc.shared_device.oem.code.statistics.services.CityAreaDayStatisticsService;
import com.gzhryc.shared_device.oem.code.statistics.services.ProjectDayStatisticsService;
import com.gzhryc.shared_device.oem.h5.mng.dto.OrderChartsData;
import com.gzhryc.system.ManagerService;
import com.gzhryc.system.SysConstants;
import com.gzhryc.system.dao.db.Manager;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

public class IndexController {

	static Logger log = Logger.getLogger(IndexController.class);
	
	@Route(value={"/index.html","/"})
	public String index(HttpServletRequest request){
		return "/index.html";
	}
	
	@Route(value={"/console.html"})
	public String main(HttpServletRequest request) {
		Date currentDate = new Date();
		Long profitMoney = ProjectWalletService.self().sumMoney();
		request.setAttribute("profitMoneyStr",NumberTools.getMoneyLiStr(profitMoney));

		ProjectSumMoneyData projectSumMoneyData = ProjectDayStatisticsService.self().sumAllMoney();
		request.setAttribute("totalOrderPayMoneyStr",projectSumMoneyData.getOrderPayMoneyStr());
		request.setAttribute("totalOrderCount",projectSumMoneyData.getOrderCount());

		ProjectDayStatistics todayStatistics = ProjectDayStatisticsService.self().getOrAddByKeys(currentDate);
		if(todayStatistics == null){
			todayStatistics = new ProjectDayStatistics();
			todayStatistics.setMaxPlaceCount(0);
			todayStatistics.setMaxDeviceCount(0);
			todayStatistics.setOrderCount(0);
			todayStatistics.setOrderMoney(0L);
			todayStatistics.setOrderPayMoney(0L);
		}

		request.setAttribute("todayStatistics",todayStatistics);

		ProjectProfitDayStatistics projectProfitDayStatistics = ProjectProfitDayStatisticsService.self().getOrAddByKeys(currentDate);
		request.setAttribute("todayProfitMoneyStr",projectProfitDayStatistics.getIncomeMoneyStr());

		Long deviceCount = DeviceService.self().countBySearch(new DeviceSearch());
		Long deployDeviceCount = DeviceService.self().countByDeploy();
		Long placeCount = PlacePhysicalStoreService.self().countJoinBySearch(new PlacePhysicalStoreSearch());
		Long agentCount = AgentService.self().countJoinBySearch(new AgentSearch());

		request.setAttribute("deviceCount",deviceCount);
		request.setAttribute("deployDeviceCount",deployDeviceCount);
		request.setAttribute("placeCount",placeCount);
		request.setAttribute("agentCount",agentCount);

		Date endDate = new Date();
		Date startDate = DateUtils.addDays(endDate,-30);

		List<ProvinceSumMoneyData> sumMoneyDataList = CityAreaDayStatisticsService.self().sumMoneyGroupProvince(startDate,endDate);
		if(sumMoneyDataList != null && sumMoneyDataList.size() > 0){
			for(int i = 0;i < sumMoneyDataList.size();i++ ) {
				ProvinceSumMoneyData p1 = sumMoneyDataList.get(i);
				for(int j = (i + 1);j < sumMoneyDataList.size();j++ ) {
					ProvinceSumMoneyData p2 = sumMoneyDataList.get(j);
					if (p2.getOrderMoney() > p1.getOrderMoney()) {
						sumMoneyDataList.set(i, p2);
						sumMoneyDataList.set(j, p1);
						i = 0;
						break;
					}
				}
			}
			List<Map<String,Object>> provinceBusinessMoneyList = new ArrayList<>();
			for(int i=0;i<6 && i < sumMoneyDataList.size();i++) {
				ProvinceSumMoneyData p1 = sumMoneyDataList.get(i);
				Map<String, Object> data = new HashMap<>();
				data.put("name",p1.getProvince());
				data.put("value", p1.getOrderMoneyStr());
				provinceBusinessMoneyList.add(data);
			}
			request.setAttribute("provinceBusinessMoneyList",provinceBusinessMoneyList);
		}

		Long memberAllMoney = MemberWalletService.self().sumMoney();
		request.setAttribute("memberAllMoneyStr", NumberTools.getMoneyLiStr(memberAllMoney));

		Long userAllMoney = UserWalletService.self().sumMoney();
		request.setAttribute("userAllMoneyStr", NumberTools.getMoneyLiStr(userAllMoney));
		
		//项目服务费钱包
		Long serverMoney = ProjectWalletService.self().sumMoneyByType(ProjectWalletEnum.Type.ServerWallet.index());
		request.setAttribute("projectServerMoneyStr", NumberTools.getMoneyLiStr(serverMoney));
		
		return "/console.html";
	}

	@Route(value={"/console/order/charts.data"})
	public OrderChartsData getConsoleOrderCharts(){
		OrderChartsData result = new OrderChartsData(DtoConstants.NULL_DATA,"暂无数据");

		Date endDate = new Date();
		Date startDate = DateUtils.addDays(endDate,-20);
		List<ProjectDayStatistics> projectDayStatisticsList = ProjectDayStatisticsService.self().findByDate(startDate,endDate);

		EchartsOption option = new EchartsOption();
		option.setTitle(new Title());
		option.getTitle().setText("近20日营业额趋势");
		option.setTooltip(new Tooltip());

		option.setxAxis(new Axis());
		option.getxAxis().setType(Axis.Type_Category);
		option.getxAxis().setData(new ArrayList<>());

		option.setyAxis(new Axis());
		option.getyAxis().setType(Axis.Type_Value);

		option.setSeries(new ArrayList<>());
		SeriesItem item = new SeriesItem();
		item.setName("营业额");
		item.setType(SeriesItem.Type_Line);
		item.setSmooth(true);
		item.setItemStyle(new SeriesItem.ItemStyle());
		item.getItemStyle().setNormal(new SeriesItem.ItemStyleNormal());
		item.getItemStyle().getNormal().setAreaStyle(new SeriesItem.AreaStyle());
		item.setData(new ArrayList<>());


		for(int i = 0;i <= 21;i++){
			Date temp = DateUtils.addDays(startDate,i);
			String dayDate = DateFormatUtils.format(temp,"yyyyMMdd");

			option.getxAxis().getData().add(DateFormatUtils.format(temp,"MM-dd"));

			boolean flag = true;
			if(projectDayStatisticsList != null && projectDayStatisticsList.size() > 0){
				for(ProjectDayStatistics dayStatistics : projectDayStatisticsList){
					if(dayStatistics.getDayDate().equals(dayDate)){
						item.getData().add(dayStatistics.getOrderMoneyStr());
						flag = false;
						break;
					}
				}
			}

			if(flag){
				item.getData().add(0);
			}
		}
		option.getSeries().add(item);

		result.setCode(DtoConstants.SUCCESS,null);
		result.getBody().setOptionList(new ArrayList<>());
		result.getBody().getOptionList().add(option);

		return result;
	}

	@Route(value={"/console/map/charts.data"})
	public OrderChartsData getConsoleMapCharts(){
		OrderChartsData result = new OrderChartsData(DtoConstants.NULL_DATA,"暂无数据");

		Double maxValue = 30D;

		EchartsOption option = new EchartsOption();
		option.setTitle(new Title());
		option.getTitle().setText("近30天省级营业额");
		option.setTooltip(new Tooltip());
		option.getTooltip().setTrigger(Tooltip.Trigger_Item);

		option.setDataRange(new DataRange());
		option.getDataRange().setOrient(DataRange.Orient_Horizontal);
		option.getDataRange().setMin(0);
		option.getDataRange().setMax(maxValue.intValue());
		option.getDataRange().setText(new ArrayList<>());
		option.getDataRange().getText().add("高");
		option.getDataRange().getText().add("低");
		option.getDataRange().setSplitNumber(0);

		option.setSeries(new ArrayList<>());
		SeriesItem item = new SeriesItem();
		item.setName("区域营业额");
		item.setType(SeriesItem.Type_Map);
		item.setMapType(SeriesItem.MapType_China);
		item.setSelectedMode(SeriesItem.SelectedMode_Multiple);
		item.setItemStyle(new SeriesItem.ItemStyle());
		item.getItemStyle().setNormal(new SeriesItem.ItemStyleNormal());
		item.getItemStyle().getNormal().setLabel(new SeriesItem.Label());
		item.getItemStyle().setEmphasis(new SeriesItem.ItemStyleEmphasis());
		item.getItemStyle().getEmphasis().setLabel(new SeriesItem.Label());

		Date endDate = new Date();
		Date startDate = DateUtils.addDays(endDate,-30);

		List<ProvinceSumMoneyData> sumMoneyDataList = CityAreaDayStatisticsService.self().sumMoneyGroupProvince(startDate,endDate);

		item.setData(new ArrayList<>());

		List<Long> keys = ChinaProvince.getKeys();
		for(Long key : keys){
			Map<String,Object> data = new HashMap<>();
			data.put("name",ChinaProvince.getName(key));
			data.put("value",0);
			if(sumMoneyDataList != null && sumMoneyDataList.size() > 0) {
				CountryArea area = CountryAreaUtils.getProvince(key);
				if (area != null) {
					for(ProvinceSumMoneyData sumMoneyData : sumMoneyDataList){
						if(sumMoneyData.getProvince().equals(area.getName())){
							Double value = NumberTools.changeMoneyLi(sumMoneyData.getOrderMoney());
							if(value > maxValue){
								maxValue = value;
							}
							data.put("value", sumMoneyData.getOrderMoneyStr());
							break;
						}
					}
				} else {
					log.error("未找到{{0}}的省信息", ChinaProvince.getName(key));
				}
			}
			item.getData().add(data);
		}

		option.getDataRange().setMax(maxValue.intValue() + 10);

		option.getSeries().add(item);

		result.setCode(DtoConstants.SUCCESS,null);
		result.getBody().setOptionList(new ArrayList<>());
		result.getBody().getOptionList().add(option);

		return result;
	}

	@Route(value={"/login.html"},method="GET")
	public String login(){
		return "/login.html";
	}
	
	@Route(value={"/verifyCode.jpeg"})
	public void vie(HttpServletRequest request,HttpServletResponse response,HttpSession session) {
		Integer width = WebUtils.getInteger(request, "w",250);
		Integer height = WebUtils.getInteger(request, "h",50);
		VerifyCode verifyCode = VerifyCodeTools.createImg(width, height, 5);
		if(verifyCode != null) {
			session.setAttribute(SysConstants.SESSION_VERFITY_CODE, verifyCode.getCode());
			WebUtils.exportJPEG(response, verifyCode.getImg());
		}
	}
	
	@Route(value={"/login.do"},method="POST")
	public AjaxResult doLogin(HttpServletRequest request,HttpServletResponse response,HttpSession session){
		AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"登陆失败，请检查账号或密码");
		String loginName = request.getParameter("loginName");
		String loginPwd = request.getParameter("loginPwd");
		String vercode = request.getParameter("vercode");
		String remember = request.getParameter("remember");
		
		String verifyCode = WebUtils.getAttribute(session, SysConstants.SESSION_VERFITY_CODE, String.class);
		if(StringUtils.isNotBlank(vercode) && vercode.toUpperCase().equals(verifyCode)){
			if(StringUtils.isNotBlank(loginName) && StringUtils.isNotBlank(loginPwd)){
				try{
					Manager manager = ManagerService.self().login(loginName, loginPwd);
					if(manager != null){
						session.setAttribute(SysConstants.SESSION_LOGIN_MANAGER, manager);
						result.setCode(DtoConstants.SUCCESS, null);
						result.setBody(manager.getToken());
						
						if(StringTools.isNotBlank(remember) && "on".equals(remember)) {
							//默认30天
							Integer time = 30 * 24 * 60 * 60;
							WebUtils.setCookies(request, response, SysConstants.COOKIES_LOGIN_TOKEN, manager.getToken(), time);
						}else {
							WebUtils.setCookies(request, response, SysConstants.COOKIES_LOGIN_TOKEN, "", 3);
						}
					}
				}catch(LogicException e){
					result.setMsg(e.getMessage());
				}catch(Exception e){
					result.setMsg(e.getMessage());
				}
			}else{
				result.setMsg("请填写账号或密码");
			}
		}else {
			result.setMsg("验证码不正确");
		}
		return result;
	}
	
	@Route(value={"/logout.do"})
	public AjaxResult logout(HttpServletRequest request,HttpServletResponse response,HttpSession session){
		AjaxResult result = new AjaxResult(DtoConstants.SUCCESS);
		Manager manager = WebUtils.getAttribute(session, SysConstants.SESSION_LOGIN_MANAGER, Manager.class);
		if(manager != null) {
			ManagerService.self().logout(manager.getId());
		}
		session.invalidate();
		//设置为空
		WebUtils.setCookies(request, response, SysConstants.COOKIES_LOGIN_TOKEN, "", 3);
		return result;
	}

	@Route(value={"/about.html"},method="GET")
	public String about(HttpServletRequest request){
		request.setAttribute("version", BaseConstants.VERSION);
		return "/about.html";
	}
}
